package com.uhylab.uhuvinetest.utils.refresh;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.uhylab.uhuvinetest.R;

/**
 * 项目名称：Uhylab
 * 类描述：
 * 创建人：xyb
 * 创建时间：16/8/31 21:42
 * 修改人：xyb
 * 修改时间：16/8/31 21:42
 * 修改备注：
 */
public class MyRefreshLayout extends SwipeRefreshLayout implements AbsListView.OnScrollListener {
    private ListView mListView;
    private OnLoadListener mOnLoadListener;
    private boolean isLoading;
    private View listFootView;

    public MyRefreshLayout(Context context) {
        super(context, null);
    }

    public MyRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        listFootView = View.inflate(context, R.layout.list_foodview, null);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (mListView == null) {
            getListView();
        }

    }

    private void getListView() {
        int childCount = getChildCount();
        if (childCount > 0) {
            View childView = getChildAt(0);
            if (childView instanceof ListView) {
                mListView = (ListView) childView;
                mListView.setOnScrollListener(this);
            }
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (mListView.getLastVisiblePosition() == mListView.getAdapter().getCount() - 1 &&
                !isLoading) {
            setLoading(true);
            mOnLoadListener.onLoad();
        }
    }



    public void setLoading(boolean loading) {
        isLoading = loading;
        if (isLoading) {
            mListView.addFooterView(listFootView);
        } else {
            try {
                mListView.removeFooterView(listFootView);
            } catch (Exception e) {
            }
        }
    }


    public void setOnLoadListener(OnLoadListener onLoadListener) {
        mOnLoadListener = onLoadListener;
    }

    public interface OnLoadListener {
        public void onLoad();
    }


}
